import os
import time

import xlwt
from flask import request, Response
from Database import TablesInterface, init as DatabaseInit
from WEB.app.Decorator.Login import pc_login_required


@pc_login_required
def download():
    email = request.form.get('email')
    # 准备表格
    excel_name = '网红爬取个人数据报表'
    # .encode("utf-8").decode("latin1")
    wb = xlwt.Workbook()
    ws = wb.add_sheet(excel_name)
    first_col = ws.col(0)  # xlwt中是行和列都是从0开始计算的
    second_col = ws.col(1)
    third_col = ws.col(2)
    four_col = ws.col(3)
    five_col = ws.col(4)
    first_col.width = 128 * 20
    second_col.width = 230 * 20
    third_col.width = 230 * 20
    four_col.width = 128 * 20
    five_col.width = 230 * 20
    ws.write(0, 0, "ID")
    ws.write(0, 1, "运营者ID")
    ws.write(0, 2, "网红来源")
    ws.write(0, 3, "网红主页")
    ws.write(0, 4, "网红昵称")
    ws.write(0, 5, "网红邮箱")
    ws.write(0, 6, "网红粉丝数")
    ws.write(0, 7, "网红爬取时间")
    ws.write(0, 8, "运营者名称")
    ws.write(0, 9, "运营者昵称")
    ws.write(0, 10, "运营者邮箱")
    mysql = DatabaseInit.init()
    cursor = mysql.cursor()
    cursor.execute('select * from `' + TablesInterface.table_celebrity +
                   '` c left join `' + TablesInterface.table_operator +
                   '` o on o.id = c.operator_id where o.email="' + email + '"')
    excel_data = cursor.fetchall()
    for i, row in enumerate(excel_data):
        ws.write(i + 1, 0, row[0])
        ws.write(i + 1, 1, row[1])
        ws.write(i + 1, 2, row[2])
        ws.write(i + 1, 3, row[3])
        ws.write(i + 1, 4, row[4])
        ws.write(i + 1, 5, row[5])
        ws.write(i + 1, 6, row[6])
        ws.write(i + 1, 7, row[7])
        ws.write(i + 1, 8, row[9])
        ws.write(i + 1, 9, row[10])
        ws.write(i + 1, 10, row[11])
        pass
    # 当前时间戳
    now = str(time.time())
    # file_name = "celebrity_" + excel_name + now + ".xls"
    file_name = "celebrity_" + now + ".xls"
    file_dir = os.getcwd() + "/static/excel/"
    file_path = file_dir + file_name
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    try:
        f = open(file_path, 'r')
        f.close()
    except IOError:
        f = open(file_path, 'w')
        pass
    wb.save(file_path)

    # 发送文件
    with open(file_path, 'rb') as f:
        data = f.readlines()
    os.remove(file_path)
    return Response(data, headers={
        'Content-Type': 'application/x-xls',
        'Content-Disposition': 'attachment; filename=%s;' % file_name
    })
